package cn.edu.seu.herald.informationplatform.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import cn.edu.seu.herald.informationplatform.bean.league.LeagueInfo;
import cn.edu.seu.herald.informationplatform.bean.league.LeagueUser;
import cn.edu.seu.herald.informationplatform.bean.league.Picture;
import cn.edu.seu.herald.informationplatform.dao.cookie.LeagueUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueInfoDao;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueUserDao;
import cn.edu.seu.herald.informationplatform.dao.database.PictureDao;
import cn.edu.seu.herald.informationplatform.util.filetools.PicTools;

public class PortraitUpload extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public PortraitUpload() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try{
		LeagueUserSessionCookieAccess luSessionCookieAccess =new LeagueUserSessionCookieAccess(request);
		response.setContentType("text/html");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		boolean isMultipart = ServletFileUpload.isMultipartContent(
				  request);
				  if (!isMultipart) {
				  System.out.println("File Not Uploaded");
				  } else {
				  FileItemFactory factory = new DiskFileItemFactory();
				  ServletFileUpload upload = new ServletFileUpload(factory);
				  List<?> items = null;
				  try {
				  items = upload.parseRequest(request);
				  System.out.println("items: "+items);
				  } catch (FileUploadException e) {
				  e.printStackTrace();
				  }
				  Iterator<?> itr = items.iterator();
				  
				  while (itr.hasNext()) {		    
						  FileItem itemPic = (FileItem) itr.next();
						  if (!itemPic.isFormField()){
							  if(itemPic.getName()!=null&&itemPic.getName()!="")
							  {
							  System.out.println("HERE");
							  String itemName = FilenameUtils.getName(itemPic.getName());
							  Random generator = new Random();
							  int r = Math.abs(generator.nextInt());

							  String reg = "[.*]";
							  String replacingtext = "";
							  
							  Pattern pattern = Pattern.compile(reg);
							  Matcher matcher = pattern.matcher(itemName);
							  StringBuffer buffer = new StringBuffer();

							  while (matcher.find()) {
							  matcher.appendReplacement(buffer, replacingtext);
							  }
							  int IndexOf = itemName.indexOf("."); 
							  String preFileName = itemName.substring(IndexOf);
							  /*System.out.println("preFileName: "+preFileName);
				              System.out.println("fileName:" + buffer.toString());
				              System.out.println("fileType:" + item.getContentType());
				              System.out.println("fileSize:" + item.getSize() + "byte");*/
							  String finalimage = buffer.toString()+"_"+r+preFileName;
							  System.out.println("Final Image==="+finalimage);
							  String path = getServletContext().getRealPath("/");
							  Properties pro = System.getProperties();
						         String osName = pro.getProperty("os.name");
						         File saveFile = null;
						         String savePath = null;
						         String relativeSavePath = null;
						         
						         if("Linux".equals(osName) || "linux".equals(osName) || "LINUX".equals(osName)){
						        	 savePath = path+"/pictures/"+finalimage;
						        	 saveFile = new File(savePath); 
						        	
						         }
						         else{
						        	 savePath = path+"pictures\\"+finalimage;
						        	 saveFile = new File(savePath);
						         }
						         relativeSavePath = "pictures/"+finalimage;
							  itemPic.write(saveFile); 							 
							  PicTools.correctPicSize(savePath);
							 LeagueInfoDao leagueInfoDao = LeagueInfoDao.getDao();
							 LeagueUserDao leagueUserDao = LeagueUserDao.getDao();
							 LeagueUser  leagueUser = leagueUserDao.getLeagueUser(luSessionCookieAccess.getLeagueId());
							 int leagueInfoId = leagueUser.getLeagueInfoId();
							 LeagueInfo leagueInfo = leagueInfoDao.getLeagueInfo(leagueInfoId);
							 String preRealPath = path+leagueInfo.getPortrait();
						     File prefile = null;
						     if("Linux".equals(osName) || "linux".equals(osName) || "LINUX".equals(osName)){
						    	 prefile = new File(preRealPath);  
						     }else{
						    	 prefile = new File(preRealPath.replaceAll("\\\\", "/"));
						     }
						     if (prefile.isFile() && prefile.exists()) {  
						    	 prefile.delete();  
							 }  
							 leagueInfoDao.updateLeaguePortrait(leagueInfoId,relativeSavePath);
						  }
				  }
					  }
				
				  }

				  response.sendRedirect("./home.jsp?league="+luSessionCookieAccess.getLeagueId()); //定向的页面
				
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
